/* customMessage.js */

const app = getApp();

Page({
	data: {
		to: null,
		number : '',
		goods : '',
		price : '',
	},
	onLoad(options) {
		this.setData({
			to: JSON.parse(options.to)
		});
	},
	setNumber(e){
		this.setData({
			number: e.detail.value
		});
	},
	setGoods(e){
		this.setData({goods: e.detail.value});
	},
	setPrice(e){
		this.setData({
			price: e.detail.value
		});
	},
	sendCustomMessage () {
		let customMessage = wx.im.createCustomMessage({
			type : 'order',
			payload : {
				number : this.data.number,
				goods : this.data.goods,
				price : this.data.price
			},
			to : {
				id : this.data.to.id,
				type : this.data.to.type,
				data : {name : this.data.to.name, avatar: this.data.to.avatar}
			}
		});
		let type = this.data.to.type;
		if(type  === wx.GoEasyIM.SCENE.PRIVATE){
			// 私聊
			let friendId = this.data.to.id;
			console.log("friendId:"+friendId);
			let messages = app.globalData.imService.getPrivateMessages(friendId);
			messages.push(customMessage);
		}else {
			// 群聊
			let groupId = this.data.to.id;
			let groupMessages = app.globalData.imService.getGroupMessages(groupId);
			groupMessages.push(customMessage);
		}
		// 发送自定义消息
		let promise = wx.im.sendMessage(customMessage);
		promise.then((res) => {
			console.log('发送消息成功');
			wx.navigateBack();
		})
		.catch(e => {
			console.log(e)
		});
	},
	cancel () {
		wx.navigateBack()
	}
})
